<template>
	<el-row :gutter="15">
		<el-col :span="24">
			<new-table v-bind="state" @handleSizeChange="onHandleSizeChange"
				@handleCurrentChange="onHandleCurrentChange">

				<template #search>
					<new-form :formOptions="formOptions" :searchForm="searchForm" @search="onSearch" />
				</template>

				<template #operation="scope">
					<el-link type="primary" :underline="false" @click="openDetail(scope.row, HandleType.EIDT)">编辑
					</el-link>
					<el-popconfirm title="确定删除吗？" @confirm="onHandleDelete(scope.row)">
						<template #reference>
							<el-link type="danger" :underline="false">删除</el-link>
						</template>
					</el-popconfirm>
					<el-link type="primary" :underline="false" @click="openResetPW(scope.row.id)">修改密码
					</el-link>
				</template>

				<template #btn>
					<el-button type="primary" @click="openDetail(null, HandleType.ADD)">
						+ 新增用户
					</el-button>
				</template>
			</new-table>
			<HandleModal ref="handleModalRef" v-bind="HandleModalProps" />
			<HandleModal ref="handleModalRef_pw" v-bind="HandleModalProps_pw" />
		</el-col>
	</el-row>
</template>

<script setup lang="ts" name="FormTableDemoExample">
import { onMounted, reactive, toRefs, ref, h, watchEffect } from "vue";
import NewTable from 'src/components/NewTable/index.vue'
import NewForm from 'src/components/NewForm/index.vue'
import HandleModal from '../components/HandleModal.vue'
// import icon_edit from 'src/assets/image/icon_edit.svg'
// import icon_add from 'src/assets/image/icon_add.svg'
// import icon_delete from 'src/assets/image/icon_delete.svg'
import { StateList, RoleList, UserStateList } from "src/pages/clueManager/const";
import { ElTag } from "element-plus";
import { HandleType } from "src/pages/clueManager/const";
import { getUserSearch, postUserAdd, postUserModify, postResetPW, getUserDel } from "../api";
import { useValidateDepartmentList } from "src/hooks";
import utils from "src/utils";
import { regExp_phone } from "src/common/const/reg-exp";

const handleModalRef = ref<InstanceType<typeof HandleModal> | null>(null);
const handleModalRef_pw = ref<InstanceType<typeof HandleModal> | null>(null);
const [validateDepartmentList] = useValidateDepartmentList();
const renderCB = (groups: any[], value: any, index: number, key_val = 'value', key_key = 'label'): any => {
	const newVal = (groups.filter(group => `${group[key_val]}` === `${value}`)[0] || {})[key_key]
	const newType = `${value}` === '2' ? 'danger' : 'primary'
	return h(ElTag, {
		// @ts-ignore
		class: `el-tag--${newType}`
	}, newVal)
}
const state = reactive({
	tableHeader: <TableHeader[]>[
		{ label: "姓名", prop: "name" },
		{ label: "用户名", prop: "loginname" },
		{ label: "部门", prop: "departmentName" },
		{ label: "手机号码", prop: "mobile" },
		{ label: "状态", prop: "status", render: (value: any, _: any, index: number) => renderCB(UserStateList, value, index) },
		{ label: "创建时间", prop: "addtime", width: 200 },
		{
			label: "操作",
			fixed: "right",
			slotKey: "operation",
			width: 180,
		},
	],
	//表项数据
	tableData: <any[]>[],
	formOptions: <FormOptions[]>[],
	//这里允许动态属性所以可为空
	searchForm: <SearchFormType>{},
	isShowSearchRegion: true,
	isShowBtnRegion: true,
	pageNum: 1,
	pageSize: 10,
	total: 0,
	tableHeight: "calc(100vh - 302px)",
	isIndex: false,
});
const { formOptions, searchForm, pageNum, pageSize } = toRefs(state);
const handleFormOptions = (type: string):FormOptions[] => {
	return [
	{
		type: "input",
		props: {
			label: "姓名",
			placeholder: "请输入姓名",
			clearable: true,
		},
		vm: "name",
		span: 24,
		required: true
	},
	{
		type: "select",
		props: {
			label: "归属部门",
			placeholder: "请选择归属部门",
			clearable: true,
		},
		vm: "departmentid",
		selectOptions: [...validateDepartmentList],
		span: 24,
		required: true,
	},
	{
		type: "input",
		props: {
			label: "手机号码",
			placeholder: "请输入手机号码",
			clearable: true,
		},
		span: 24,
		vm: "mobile",
		rules: [{ pattern: regExp_phone, message: '请填写正确的手机号码', trigger: 'blur' }]
	},
	{
		type: "input",
		props: {
			label: "用户名",
			placeholder: "请输入用户名",
			clearable: true,
			disabled: type === HandleType.EIDT
		},
		span: 24,
		required: true,
		vm: "loginname"
	},
	{
		type: "input",
		props: {
			label: "用户密码",
			placeholder: "请输入用户密码",
			clearable: true,
			disabled: type === HandleType.EIDT,
			type: 'password'
		},
		isHidden: type === HandleType.EIDT,
		span: 24,
		vm: "pw",
		required: true,
		rules: [{ pattern: /^[^\s,",'\\]{6,18}$/, message: '除空格、逗号、单双引号、反斜杠外组成的6-18位密码', trigger: 'blur' }]
	},
	{
		type: "radio",
		props: {
			label: "状态",
			placeholder: "请选择状态",
			clearable: true,
		},
		vm: "status",
		span: 24,
		selectOptions: [...UserStateList]
	},
	{
		type: "select",
		props: {
			label: "角色",
			placeholder: "请选择角色",
			clearable: true,
		},
		vm: "roleid",
		span: 24,
		selectOptions: [...RoleList]
	}
	
]
}
const handleFormOptions_pw: FormOptions[] = [
	{
		type: "input",
		props: {
			label: "旧密码",
			placeholder: "请输入旧密码",
			clearable: true,
			type: 'password'
		},
		vm: "pw",
		span: 24,
		required: true
	},
	{
		type: "input",
		props: {
			label: "新密码",
			placeholder: "请输入新密码",
			clearable: true,
			type: 'password'
		},
		vm: "new_pw",
		span: 24,
		required: true,
		rules: [{ pattern: /^[^\s,",'\\]{6,18}$/, message: '除空格、逗号、单双引号、反斜杠外组成的6-18位密码', trigger: 'blur' }]
	},
	{
		type: "input",
		props: {
			label: "确认密码",
			placeholder: "请输入新密码",
			clearable: true,
			type: 'password'
		},
		vm: "new_pw_repeat",
		span: 24,
		required: true,
		rules: [{ pattern: /^[^\s,",'\\]{6,18}$/, message: '除空格、逗号、单双引号、反斜杠外组成的6-18位密码', trigger: 'blur' }]
	}
	
]
const HandleModalProps_pw = reactive<any>({
	requestFunc: postResetPW,
	callbackFunc: () => {
		handleModalRef.value?.closeDialog();
		getTableList();
	},
	editData: {},
	defaultData: {
	},
	requestParams: {},
	handleType: HandleType.ADD,
	title: '修改密码',
	handleFormOptions: [...handleFormOptions_pw]
})
const openResetPW = (id: string|number) => {
	HandleModalProps_pw.requestParams.userid = id;
	handleModalRef_pw.value?.openDialog();
}
const HandleModalProps = reactive<any>({
	requestFunc: postUserAdd,
	callbackFunc: () => {
		handleModalRef.value?.closeDialog();
		getTableList();
	},
	editData: {},
	defaultData: {
	},
	handleType: HandleType.ADD,
	title: '',
	handleFormOptions: []
})
const openDetail = (row: any, type: string) => {
	console.log(row);
	if (type === HandleType.ADD) {
		HandleModalProps.editData = {}
		HandleModalProps.title = '新增用户'
		HandleModalProps.requestFunc = postUserAdd
	} else {
		HandleModalProps.editData = { ...row }
		if (HandleModalProps.editData.departmentName) {
			delete HandleModalProps.editData.departmentName
		}
		HandleModalProps.title = '编辑用户'
		HandleModalProps.requestFunc = postUserModify
	}
	HandleModalProps.handleType = type
	HandleModalProps.handleFormOptions = handleFormOptions(type)
	handleModalRef.value?.openDialog();
}
//页容量改变
const onHandleSizeChange = (val: number) => {
	// console.log('页容量 ==>：', val);
	pageSize.value = val;
	getTableList();
};
//当前分页改变
const onHandleCurrentChange = (val: number) => {
	// console.log('当前页 🚀 ==>：', val);
	pageNum.value = val;
	getTableList();
};

const _getUserDel = (id: number | string) => {
	getUserDel({ userid: id }).then((res) => {
		utils.commonNotification({
			condition: `${res.code}` === '0',
			msg_success: '删除成功',
			callback_success: () => getTableList()
		})
	});
}

// 删除
const onHandleDelete = (row: any) => {
	_getUserDel(row.id)
};

// 获取表项数据
const getTableList = () => {
	let params = { ...searchForm.value };
	getUserSearch({
		page: pageNum.value,
		size: pageSize.value,
		...params
	}).then((res) => {
		if (`${res.code}` === '0') {
			const { total, userVOList } = res.data;
			state.total = total;
			state.tableData = [...userVOList]
		} else {
			state.total = 0;
			state.tableData = []
		}
	});
};

const onSearch = (isReset?: string) => {
	pageNum.value = isReset ? 1 : pageNum.value;
	getTableList();
};
watchEffect(() => {
	state.formOptions = [
		{
			type: "input",
			props: {
				label: "姓名",
				placeholder: "请输入姓名",
				clearable: true,
			},
			vm: "name"
		},
		{
			type: "input",
			props: {
				label: "用户名",
				placeholder: "请输入用户名",
				clearable: true,
			},
			vm: "loginname"
		},
		{
			type: "input",
			props: {
				label: "手机号码",
				placeholder: "请输入手机号码",
				clearable: true,
			},
			rules: [{ pattern: regExp_phone, message: '请填写正确的手机号码', trigger: 'blur' }],
			vm: "mobile"
		},
		{
			type: "select",
			props: {
				label: "状态",
				placeholder: "请选择状态",
				clearable: true,
			},
			vm: "status",
			selectOptions: [...UserStateList]
		},
		{
			type: "select",
			props: {
				label: "部门",
				placeholder: "请选择部门",
				clearable: true,
			},
			vm: "departmentid",
			selectOptions: [...validateDepartmentList]
		},
	]
})
onMounted(() => getTableList());
</script>

<style scoped lang="scss">
.box-card {
	margin-top: 15px;
	padding-left: 20px;

	.custom-card {
		min-height: 500px;
	}
}
</style>